package com.playball.lottery.frm.set;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.LoadingDialog;
import com.playball.lottery.customview.ShowCustomDialog;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.eventmanger.EventManager;
import com.playball.lottery.eventmanger.EventType;
import com.playball.lottery.frm.yhzx.JddKeFuActivity;
import com.playball.lottery.nt.AppVersionConfig;
import com.playball.lottery.nt.GetJsonData;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.sessions.SessionManager;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.SysApplication;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.Unicorn;

import static com.playball.lottery.JddMainActivity.USERID;


/**
 * 设置页面
 * 
 * @author Administrator
 * 
 */
public class SetMainActivity extends BaseActivity implements DefConstants {
	private View kjnotice;
	private View shoushimima;
	// private View logout;
	// private View update;
	private View about;
	private View help;
	private View contact;
	private View suggest;
	private View share;
	private View update;
	private Button set_info_exit;
	// private View exit;

	// private View register_line;
	// private View login_line;
	// private View logout_line;
	String userName;
	String userPwd;
	private boolean bJump2YHZX = false;

	private ShowTipDialog showdialog = new ShowTipDialog();
	/** 运行上下文 */
	private Context context;

	private static String packgeName;
	private String newVerName = "";
	private int newVerCode = 0;
	LoadingDialog pBar;
	private Handler handler = new Handler();

	SharedPreferences sp;

	SessionManager session;

	// /** 进球声音提示 */
	// private CheckBox cb1;
	// /** 红黄牌声音提示 */
	// private CheckBox cb2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.context = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.set_main);
		SysApplication.getInstance().addActivity(this);

		session = new SessionManager(getApplicationContext());

		// 标题
		TitleBar();
		sp = context.getSharedPreferences("userNamesFile", Activity.MODE_PRIVATE);
		kjnotice = findViewById(R.id.set_info_kjnotice);
		shoushimima = findViewById(R.id.set_info_shoushimima);
		shoushimima.setVisibility(View.GONE);
		// logout = findViewById(R.id.set_info_logout);
		// update = findViewById(R.id.set_info_update);
		about = findViewById(R.id.set_info_about);
		help = findViewById(R.id.set_info_help);
		contact = findViewById(R.id.set_info_contact);
		suggest = findViewById(R.id.set_info_suggest);
		share = findViewById(R.id.set_info_share);
		update = findViewById(R.id.set_info_update);
		set_info_exit = (Button) findViewById(R.id.set_info_exit);
		// exit = findViewById(R.id.set_info_exit);
		// // 声音提示
		// cb1 = (CheckBox) findViewById(R.id.set_cb_hint1);
		// cb2 = (CheckBox) findViewById(R.id.set_cb_hint2);

		// register_line = findViewById(R.id.set_info_register_line);
		// login_line = findViewById(R.id.set_info_login_line);
		// logout_line = findViewById(R.id.set_info_logout_line);

		// app = (ApplicationBall) getApplication();
		// processLoginOrLonout();

		// // 进球声音提示
		// // 根据存贮的设置决定checkbox的选中状态
		// if (MyPreference.getInstance(context).getSoundFlgJQ()) {
		// // 默认为选中
		// cb1.setChecked(true);
		// } else {
		// cb1.setChecked(false);
		// }
		//
		// cb1.setOnCheckedChangeListener(new
		// CompoundButton.OnCheckedChangeListener() {
		// public void onCheckedChanged(CompoundButton buttonView, boolean
		// isChecked) {
		// if (isChecked) {
		// // 存贮数据 "选中");
		// MyPreference.getInstance(context).storeSoundFlgJQ(true);
		// } else {
		// MyPreference.getInstance(context).storeSoundFlgJQ(false);
		// }
		// }
		// });

		// // 红黄牌声音提示
		// if (MyPreference.getInstance(context).getSoundFlgHH()) {
		// // 默认为选中
		// cb2.setChecked(true);
		// } else {
		// cb2.setChecked(false);
		// }
		// cb2.setOnCheckedChangeListener(new
		// CompoundButton.OnCheckedChangeListener() {
		// public void onCheckedChanged(CompoundButton buttonView, boolean
		// isChecked) {
		// if (isChecked) {
		// // 存贮数据 "选中");
		// MyPreference.getInstance(context).storeSoundFlgHH(true);
		// } else {
		// MyPreference.getInstance(context).storeSoundFlgHH(false);
		// }
		// }
		// });

		kjnotice.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// SetMainActivity.this.startActivityForResult(
				// new Intent().setClass(SetMainActivity.this,
				// JddRegisterActivity.class),
				// REQ_CODE_SETMAIN_2_REG);
				SetMainActivity.this.startActivityForResult(
						new Intent().setClass(SetMainActivity.this, SetKJNoticeActivity.class), REQ_CODE_SET_KJNOTICE);
			}
		});

		// shoushimima.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// startActivityForResult(
		// new Intent().setClass(SetMainActivity.this, LoginActivity.class),
		// REQ_CODE_SETMAIN);
		// }
		// });

		// logout.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// // 注销
		// AlertDialog.Builder alertbBuilder = new
		// AlertDialog.Builder(SetMainActivity.this);
		// alertbBuilder.setTitle("提示").setMessage("确认注销?")
		// .setPositiveButton("确定", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // 结束这个Activity，清空帐号信息
		// // app.onCreate();
		// processLoginOrLonout();
		// // MainActivity.setYHZX();
		// MyPreference.getInstance(SetMainActivity.this).setUserId("0");
		// }
		// }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.cancel();
		// }
		// }).create();
		// alertbBuilder.show();
		// }
		// });

		// update.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// TODO Auto-generated method stub
		// SetMainActivity.this.startActivity(new
		// Intent().setClass(SetMainActivity.this,
		// UpdateVersionActivity.class));
		// }
		// });
		about.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SetMainActivity.this.startActivity(new Intent().setClass(SetMainActivity.this, NewAboutActivity.class));
			}
		});
		help.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SetMainActivity.this.startActivity(new Intent().setClass(SetMainActivity.this, HelpActivity.class));
			}
		});
		contact.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				SetMainActivity.this.startActivity(new Intent().setClass(SetMainActivity.this, JddKeFuActivity.class));
				
				String title = "天彩在线客服";
				 // 设置访客来源，标识访客是从哪个页面发起咨询的，用于客服了解用户是从什么页面进入三个参数分别为来源页面的url，来源页面标题，来源页面额外信息（可自由定义）
				 // 设置来源后，在客服会话界面的"用户资料"栏的页面项，可以看到这里设置的值。
				 ConsultSource source = new ConsultSource("天彩Android版", "天彩简易版Android在线客服", "简易版");
				 // 请注意： 调用该接口前，应先检查Unicorn.isServiceAvailable(), 如果返回为false，该接口不会有任何动作
				 Unicorn.openServiceActivity(context, // 上下文
						 					title, // 聊天窗口的标题
				                         source // 咨询的发起来源，包括发起咨询的url，title，描述信息等
				                          );
				
				
			}
		});
		suggest.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// SetMainActivity.this.startActivity(new
				// Intent().setClass(SetMainActivity.this,
				// SuggestionActivity.class));
				SetMainActivity.this.startActivity(new Intent().setClass(SetMainActivity.this, FeedBackActivity.class));
			}
		});
		share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(Intent
						.createChooser(
								new Intent(Intent.ACTION_SEND)
										.setType("text/plain")
										.putExtra(Intent.EXTRA_TEXT,
												"天彩彩票手机购彩客户端购彩方便,数据同步,开奖快速,提款安全,下载地址:http://tcaio2o.com/APP/downApp.htm")
										.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), "分享给您的好友"));
			}
		});
		//检测更新
		update.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				System.err.println("+++++++++++++" + "执行了吗?" + "++++++++++++++");
				upAsyncLoader asyncLoader = new upAsyncLoader();
				String[] dyn = new String[2];
				JSONObject params = new JSONObject();
				try {
					// 设置请求所需参数
					// params.put("CmdID", AppVersionConfig.CommenderID);//
					params.put("CmdID", ApplicationData.getInstance().getCommenderID());
				} catch (JSONException ex) {
					// TODO Auto-generated catch block
					Log.e("error", ex.toString());
				}
				dyn[0] = params.toString();
				dyn[1] = "1";
				asyncLoader.execute(dyn);
			}
		});
		set_info_exit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 弹出对话窗
				ShowCustomDialog.Builder alertbBuilder = new ShowCustomDialog.Builder(SetMainActivity.this);
				alertbBuilder.setTitle("退出登录");
				alertbBuilder.setMessage("确定要退出登录？");
				alertbBuilder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						USERID=session.getUserIDs();
						// clear session details
						session.clearSharedPreferences();
						Editor edit = sp.edit();
						edit.putString(ApplicationData.getInstance().getUserName(), "");
						// edit.remove("last-user");
						edit.commit();

						ApplicationData.getInstance().setUserID("");
						ApplicationData.getInstance().setUserName("");
						ApplicationData.getInstance().setUserPassword("");
						ApplicationData.getInstance().setUserMoney(null);

						ApplicationData.getInstance().setRealName("");
						ApplicationData.getInstance().setCardNum("");
						ApplicationData.getInstance().setMobile("");
						ApplicationData.getInstance().setBankName("");
						ApplicationData.getInstance().setIDCardNumber("");
						ApplicationData.getInstance().setIsMobileValied(false);
						ApplicationData.getInstance().setSecurityQuestion("");
						ApplicationData.getInstance().setIsPayPwd(0);
						ApplicationData.getInstance().setBankId(0);
						ApplicationData.getInstance().setRegisterTime("");
						
						// SharedPreferences sp =
						// getActivity().getSharedPreferences("userNamesFile",
						// Activity.MODE_PRIVATE);
						// sp.edit().putString("last-user", "");
						// (SetMainActivity.this).refreshUserEvent();
						EventManager.getInstance().onEvent(EventType.EV_BLL_UI_MAIN_LOT_REFRESH, null);

						dialog.dismiss();
						SetMainActivity.this.finish();
					}
				}).setPositiveButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).createCustomDialog().show();
			}
		});
		// exit.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// AlertDialog.Builder alertbBuilder = new
		// AlertDialog.Builder(SetMainActivity.this);
		// alertbBuilder.setTitle("提示").setMessage("确认退出?")
		// .setPositiveButton("确定", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // app.onCreate();
		// SysApplication.getInstance().exit();
		//
		// }
		// }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.cancel();
		// }
		// }).create();
		//
		// alertbBuilder.show();
		// }
		// });

	}

	public void onPause() {
		super.onPause();
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		// processLoginOrLonout();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// Intent intent = new Intent(context, JddMainFrameActivity.class);
			// context.startActivity(intent);
			finish();// 销毁对象
		}
		return true;
	};

	// TitleBar标题栏
	public void TitleBar() {
		// Title信息(返回+Title)
		Button back = (Button) findViewById(R.id.top_title_back);
		back.getBackground().setAlpha(255);// 不需要返回加上这句话，透明度0~255透明度值 ，值越小越透明
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Intent intent = new Intent(context,
				// JddMainFrameActivity.class);
				// context.startActivity(intent);
				finish();// 销毁对象
			}
		});

		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText("更多");

		Button refres = (Button) findViewById(R.id.top_title_refres);
		// refres.getBackground().setAlpha(0);// 不需要刷新加上这句话，透明度0~255透明度值 ，值越小越透明
		refres.setVisibility(View.INVISIBLE);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == REQ_CODE_SETMAIN) {
			if (resultCode == RESULT_OK) {
				// processLoginOrLonout();
				// MainActivity.setYHZX();
			}
		} else if (requestCode == REQ_CODE_SETMAIN_2_REG) {
			if (resultCode == RESULT_OK) {
				bJump2YHZX = true;
				userName = data.getStringExtra("userName");
				userPwd = data.getStringExtra("userPwd");
				AsyncLoader task = new AsyncLoader();
				task.execute("101");
			}
		}

	}

	public boolean CheckUserLogin() {
		// app = (ApplicationBall) getApplication();
		if (!ApplicationData.getInstance().getLoginName().equals("")
				&& !ApplicationData.getInstance().getLoginPwd().equals("")
				|| !ApplicationData.getInstance().getUserID().equals("")) {
			return true;
		} else {
			return false;
		}
	}

	// private void processLoginOrLonout() {
	// // TODO Auto-generated method stub
	// if (!CheckUserLogin()) {
	// kjnotice.setVisibility(View.VISIBLE);
	// shoushimima.setVisibility(View.VISIBLE);
	// // logout.setVisibility(View.GONE);
	//
	// register_line.setVisibility(View.VISIBLE);
	// login_line.setVisibility(View.VISIBLE);
	// logout_line.setVisibility(View.GONE);
	// } else {
	// kjnotice.setVisibility(View.GONE);
	// shoushimima.setVisibility(View.GONE);
	// logout.setVisibility(View.VISIBLE);
	//
	// register_line.setVisibility(View.GONE);
	// login_line.setVisibility(View.GONE);
	// logout_line.setVisibility(View.VISIBLE);
	// }
	//
	// }

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		SysApplication.getInstance().removeActivity(this);
	};

	// 获取Code
	public static int getVerCode(Context context) {
		int verCode = -1;
		try {
			packgeName = context.getPackageName();
			verCode = context.getPackageManager().getPackageInfo(packgeName, 0).versionCode;
		} catch (NameNotFoundException e) {
		}
		return verCode;
	}

	// 获取Name
	public static String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo(packgeName, 0).versionName;
		} catch (NameNotFoundException e) {
		}
		return verName;

	}

	public class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(SetMainActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... params) {
			String strResult;
			try {
				// 设置请求所需参数
				JSONObject param = new JSONObject();
				param.put("Name", userName);
				param.put("Pw", userPwd);// Password
				String action = params[0];
				// 获取请求返回值
				strResult = GetRequestParams.getRequestResult(param.toString(), action, getApplicationContext());
				return strResult;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.toString());
				return null;
			}
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						// 保存用户名，密码,方便后边调用
						// app = (ApplicationBall) getApplication();
						ApplicationData.getInstance().setLoginName(userName);
						ApplicationData.getInstance().setLoginPwd(userPwd);
						// 保存登录时返回的userId进全局变量
						ApplicationData.getInstance().setUserID(js.getString("Data"));
						// processLoginOrLonout();
						if (bJump2YHZX == true) {
							// MainActivity.setYHZX();
							bJump2YHZX = false;
						}
						EventManager.getInstance().onEvent(EventType.EV_BLL_UI_MAIN_LOT_REFRESH, null);
					} else {
						Toast.makeText(SetMainActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(SetMainActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}
	}

	/**
	 * 升级版本
	 * 
	 * @author Administrator
	 * 
	 */
	class upAsyncLoader extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			// 处理后台执行的任务，在后台线程执行
			String strResult;
			// String param = new String();
			// 设置请求action
			String action = params[1];
			// 获取请求返回值
			strResult = GetRequestParams.getRequestResult(params[0], action, SetMainActivity.this);
			return strResult;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		protected void onPostExecute(String result) {
			if (result != null) {
				doNetget(result);
			} else {
				Toast.makeText(SetMainActivity.this, SetMainActivity.this.getString(R.string.problem_01),
						Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	List<Map<String, Object>> nDataList = new ArrayList<Map<String, Object>>();

	public void doNetget(String strResult) {
		try {

			// System.out.println("strResult = " + strResult);

			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			// 接下来的就是JSON对象的操作了
			if (Integer.parseInt(js.getString("Code")) == 0) {
				if ("".equals(js.getString("Data"))) {
					Toast.makeText(SetMainActivity.this, R.string.now_is_the_latest_version, Toast.LENGTH_SHORT).show();
				} else {
					nDataList = getNetData(strResult);
					String updateMes = "";
					int bupdate = 0;
					String downLoadName = "";
					String newVerName = "";
					int newVerCode = 0;
					try {
						newVerCode = Integer.parseInt(String.valueOf(nDataList.get(0).get("verCode")));
						newVerName = String.valueOf(nDataList.get(0).get("verName"));
						bupdate = Integer.parseInt(String.valueOf(nDataList.get(0).get("bupdate")));
						String message = String.valueOf(nDataList.get(0).get("Message"));
						downLoadName = String.valueOf(nDataList.get(0).get("apkname"));
						JSONArray messArray = new JSONArray(message);
						for (int i = 0; i < messArray.length(); i++) {
							updateMes = updateMes + messArray.getString(i) + "\n";
						}
					} catch (Exception e) {
						// e.printStackTrace();
						newVerCode = -1;
						newVerName = "";
						bupdate = 0;
					}
					int vercode = getVerCode(SetMainActivity.this);
					if (newVerCode > vercode) {
						if (bupdate == 1 || bupdate == 2 || bupdate < 0)
							doNewVersionUpdate(updateMes, downLoadName);
						else
							Toast.makeText(SetMainActivity.this, R.string.not_need_to_update, Toast.LENGTH_LONG).show();
						// notNewVersionShow();
					} else {
						Toast.makeText(SetMainActivity.this, R.string.not_need_to_update, Toast.LENGTH_LONG).show();
						// notNewVersionShow();
					}
				}
			} else {
				Toast.makeText(SetMainActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e) {
			Log.e("error", e.toString());
		}
	}

	private List<Map<String, Object>> getNetData(String strResult) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			list = ConvertJsonToList.getList(js.getString("Data"));
		} catch (JSONException ex) {
		}
		return list;
	}

	boolean isCancelDownload;

	// 有检测到新版本，显示下载对话框
	private void doNewVersionUpdate(String mes, final String name) {

		ShowCustomDialog dialog = new ShowCustomDialog.Builder(SetMainActivity.this).setTitle("软件更新").setMessage(mes)
		// 设置内容
				.setPositiveButton("暂不更新",// 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						}).setNegativeButton("更新", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// 点击"取消"按钮之后退出程序
						dialog.cancel();
						pBar = new LoadingDialog(SetMainActivity.this);
						{
							pBar.getDialog().setCancelable(true);
							pBar.getDialog().setOnCancelListener(new DialogInterface.OnCancelListener() {
								@Override
								public void onCancel(DialogInterface dialog) {
									// TODO Auto-generated method stub
									isCancelDownload = true;
								}
							});
						}
						// 下载新版本
						downFile(AppVersionConfig.UPDATE_SERVER + name);
					}
				}).createCustomDialog();// 创建
		// 显示对话框
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	// 下载新版本
	void downFile(final String url) {

		pBar.show();
		isCancelDownload = false;
		new Thread() {
			@SuppressWarnings("unused")
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					int pBarmax = (int) entity.getContentLength() / 1024;
					pBar.setMax(pBarmax);
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(Environment.getExternalStorageDirectory(),
								AppVersionConfig.UPDATE_SAVENAME);
						fileOutputStream = new FileOutputStream(file);

						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (pBar.getMax() > (count / 1024)) {
								pBar.setProgress(count / 1024);
							}
							if (isCancelDownload)
								break;
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					if (!isCancelDownload)
						down();
				} catch (IOException e) {
					// e.printStackTrace();
					pBar.cancel();
				}
			}

		}.start();
	}

	// 下载新版本后关闭
	void down() {
		handler.post(new Runnable() {
			public void run() {
				pBar.cancel();
				update();
			}
		});
	}

	// 下载新版本后安装
	void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(
				Uri.fromFile(new File(Environment.getExternalStorageDirectory(), AppVersionConfig.UPDATE_SAVENAME)),
				"application/vnd.android.package-archive");
		SetMainActivity.this.startActivity(intent);
	}
}